package com.cly.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cly.constant.MenuConstant;
import com.cly.domain.SysMenu;
import com.cly.mapper.SysMenuMapper;
import com.cly.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService{

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 根据用户id查菜单
     * 先判断缓存有没有
     * 有直接用
     * 没有在查询 放入缓存
     * 组装菜单
     * @param sysUserId
     * @return
     */
    @Override
    public List<SysMenu> findUserMenu(Long sysUserId) {
        //查询菜单有没有当前用户菜单
        String menuStr = redisTemplate.opsForValue().get(MenuConstant.MENU_PREFIX + sysMenuMapper);
        List<SysMenu> menus = null;
        if (StringUtils.hasText(menuStr)){
            //转一下
            menus = JSON.parseArray(menuStr,SysMenu.class);
        } else {
            //查询 在进去
            menus = sysMenuMapper.findSysUserMenu(sysUserId);
            //不等于空
            if (!CollectionUtils.isEmpty(menus)){
                //转json进去 redis设置一个过期时间
                redisTemplate.opsForValue().set(MenuConstant.MENU_PREFIX + sysUserId, JSON.toJSONString(menus), Duration.ofDays(7));

            }
        }
        //转换树形菜单
        return translateTree(menus,0L);
    }

    /**
     * 转换树形菜单
     * @param menus
     * @param pid
     * @return
     */
    private List<SysMenu> translateTree(List<SysMenu> menus, long pid) {
        //根据菜单深度来选择
        //拿到顶级菜单
        List<SysMenu> root = menus.stream()
                .filter(sysMenu -> sysMenu.getParentId().equals(pid))
                .collect(Collectors.toList());
        //循环顶级菜单 匹配子菜单
        root.forEach(r -> {
            //循环所有菜单
            List<SysMenu> child = menus.stream()
                    .filter(sysMenu -> sysMenu.getParentId().equals(r.getMenuId()))
                    .collect(Collectors.toList());
            r.setList(child);
        });
        return root;

    }
}
